﻿namespace CV.Dal.Mongo.Impl
{
    using CV.Dal.Mongo.Tools;
    using CV.Entities.Dto;
    using CV.Interfaces.Dal;
    using MongoDB.Bson.Serialization;
    using MongoDB.Bson.Serialization.IdGenerators;
    using MongoDB.Driver.Linq;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using BCryptAlias = BCrypt.Net.BCrypt;

    public class UserAO : BaseAO<User, Guid>, IUserAO
    {
        public UserAO(CVMongoClient client)
            : base(client, "User")
        {
        }

        protected override void MapEntity(BsonClassMap<User> cm)
        {
            cm.AutoMap();
            cm.SetIdMember(cm.GetMemberMap(x => x.Id).SetIdGenerator(CombGuidGenerator.Instance));
        }

        public IEnumerable<User> List(int page, string sort, bool asc, out int count)
        {
            count = 2;
            return null;
        }

        public bool ValidateUser(string username, string password)
        {
            var user = GetCollection().AsQueryable().FirstOrDefault(x => x.Login == username);
            bool result = false;

            if (user != null)
            {
                result = BCryptAlias.Verify(password, user.Password);
            }

            return result;
        }

        public override User Create(User item)
        {
            var encryptedPassword = BCryptAlias.HashPassword(
                    item.Password,
                    BCryptAlias.GenerateSalt(13)
                );
            item.Password = encryptedPassword;
            return base.Create(item);
        }
    }
}
